package main;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.List;

import javax.media.Codec;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.Demultiplexer;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaTimeSetEvent;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.Renderer;
import javax.media.RestartingEvent;
import javax.media.bean.playerbean.MediaPlayerMediaLocationEditor;
import javax.media.pim.PlugInManager;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import javazoom.spi.vorbis.sampled.convert.DecodedVorbisAudioInputStream;
import javazoom.spi.vorbis.sampled.file.VorbisAudioFileReader;

import net.sf.fmj.media.renderer.audio.JavaSoundRenderer;
import net.sf.fmj.media.renderer.video.Java2dRenderer;
import net.sf.fmj.media.renderer.video.SimpleAWTRenderer;
import net.sf.fmj.theora_java.JavaOggParser;
import net.sourceforge.jffmpeg.AudioDecoder;
import net.sourceforge.jffmpeg.JMFCodec;
import net.sourceforge.jffmpeg.VideoDecoder;
import net.sourceforge.jffmpeg.codecs.audio.vorbis.OggReader;
import net.sourceforge.jffmpeg.codecs.audio.vorbis.VorbisDecoder;
import net.sourceforge.jffmpeg.demux.ogg.OggDemux;

import org.apache.commons.lang.StringUtils;

import com.omnividea.media.renderer.video.Java2DRenderer;
import com.sun.media.MediaPlayer;
import com.sun.media.renderer.audio.AudioRenderer;
import com.sun.media.renderer.video.AWTRenderer;
import com.sun.media.renderer.video.LightWeightRenderer;

import de.humatic.dsj.rc.J2DControls;

import sun.font.FontFamily;
import utils.I18nTranslation;
import utils.SRTUtils;
import utils.SRTUtils.Severity;

/**
 * 
 *
 * @author xlouwette
 * @version $Revision:$ $Date:$ $Author:$
 */

public class SRTTreatement extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;



	public static String PATH_OF_INPUT_FILE = "";

	public static String PATH_OF_OUTPUT_FILE = "";

	public static String PATH_OF_AVI_FILE = "";

	public static final String SRT = "srt";

	public static final String SRT_EXTENSION =".srt";

	public static final String AVI = "avi";

	public static final String AVI_EXTENSION =".avi";

	private List<SRTRecord> listOfRecord = new ArrayList<SRTRecord>();
	
	private JButton inputFile ; private JButton outputFile ; private JButton inputAviFile;

	private JTextField mmStartTime; private JTextField ssStartTime; private JTextField milliStartTime;

	private JTextField mmEndTime; private JTextField ssEndTime; private JTextField milliEndTime;

	private JTextField gapInMinuteField; private JTextField gapInSecondsField; private JTextField gapInMillisecondsField; 
	
	private JTextField inputFileField; private JTextField outputFileField; private JTextField aviInputFileField;

	private JTextField srtFromField ; private JTextField srtUntilField;

	private JButton launch; private JButton clear;

	private JRadioButton jRadioOne = new JRadioButton(); private JRadioButton jRadioTwo = new JRadioButton();

	private ButtonGroup group = new ButtonGroup();

	private JMenuBar jMenuBar = new JMenuBar();

	private boolean isFirstTime = true;

	private Player player1 ;
	
	MyMediaPlayer player = new MyMediaPlayer();
	
	private JPanel video = new JPanel();

	public SRTTreatement(){

		mmStartTime = new JTextField();
		mmStartTime.setPreferredSize(new Dimension(70,20));
		mmStartTime.setText(SRTUtils.addZeroBeforeTime(0,2));
		ssStartTime = new JTextField();
		ssStartTime.setPreferredSize(new Dimension(70,20));
		ssStartTime.setText(SRTUtils.addZeroBeforeTime(0,2));
		milliStartTime = new JTextField();
		milliStartTime.setPreferredSize(new Dimension(70,20));
		milliStartTime.setText(SRTUtils.addZeroBeforeTime(0,3));
		mmEndTime = new JTextField();
		mmEndTime.setPreferredSize(new Dimension(70,20));
		mmEndTime.setText(SRTUtils.addZeroBeforeTime(0,2));
		ssEndTime = new JTextField();
		ssEndTime.setPreferredSize(new Dimension(70,20));
		ssEndTime.setText(SRTUtils.addZeroBeforeTime(0,2));
		milliEndTime = new JTextField();
		milliEndTime.setPreferredSize(new Dimension(70,20));
		milliEndTime.setText(SRTUtils.addZeroBeforeTime(0,3));
		inputFile = new JButton(I18nTranslation.FILE_INPUT_PATHNAME);
		outputFile = new JButton(I18nTranslation.FILE_OUPUT_PATHNAME);
		inputAviFile = new JButton(I18nTranslation.AVI_FILE_INPUT_PATHNAME);
		aviInputFileField = new JTextField();
		aviInputFileField.setEditable(false);
		aviInputFileField.setPreferredSize(new Dimension(270,20));
		inputFileField = new JTextField();
		inputFileField.setEditable(false);
		inputFileField.setPreferredSize(new Dimension(270,20));
		outputFileField = new JTextField();
		outputFileField.setEditable(false);
		outputFileField.setPreferredSize(new Dimension(270,20));
		srtFromField = new JTextField();
		srtFromField.setPreferredSize(new Dimension(270,20));
		srtUntilField = new JTextField();
		srtUntilField.setPreferredSize(new Dimension(270,20));
		gapInMinuteField = new JTextField();
		gapInMinuteField.setPreferredSize(new Dimension(70,20));
		gapInMinuteField.setText(SRTUtils.addZeroBeforeTime(0,2));
		gapInSecondsField = new JTextField();
		gapInSecondsField.setPreferredSize(new Dimension(70,20));
		gapInSecondsField.setText(SRTUtils.addZeroBeforeTime(0,2));
		gapInMillisecondsField = new JTextField();
		gapInMillisecondsField.setPreferredSize(new Dimension(70,20));
		gapInMillisecondsField.setText(SRTUtils.addZeroBeforeTime(0,3));
		launch = new JButton(I18nTranslation.LAUNCH);
		clear = new JButton(I18nTranslation.CLEAR);
		group.add(jRadioOne);
		jRadioOne.setSelected(true);

		srtFromField.setEditable(true);
		srtUntilField.setEditable(true);
		group.add(jRadioTwo);
		eventOnInputFile();
		eventOnOutputFile();
		eventOnLaunchButton();
		eventOnClearButton();
		eventOnJRadioButtonOne();
		eventOnJRadioButtonTwo();
		eventOnAviInputFile();
		//initializeVideo();
		//setLayout(new FlowLayout());
		
	}
	
	
	

	public void addCodec(){
		Codec vorbis; 
    	Codec video;
    	Codec audio;
    		String JFFMPEG_VIDEO = "net.sourceforge.jffmpeg.VideoDecoder";
			String JFFMPEG_AUDIO = "net.sourceforge.jffmpeg.AudioDecoder";
			String VORBIS_DECODER = "net.sourceforge.jffmpeg.codecs.audio.vorbis.VorbisDecoder";
			
			video = new VideoDecoder();
			javax.media.PlugInManager.addPlugIn(JFFMPEG_VIDEO,
			    	video.getSupportedInputFormats(),
			    	video.getSupportedInputFormats(),
			    	PlugInManager.CODEC );
			audio = new AudioDecoder();
			javax.media.PlugInManager.addPlugIn(JFFMPEG_AUDIO,
					audio.getSupportedInputFormats(),
					audio.getSupportedInputFormats(),
			    	PlugInManager.CODEC);
			vorbis = new VorbisDecoder();
			javax.media.PlugInManager.addPlugIn(VORBIS_DECODER,
					vorbis.getSupportedInputFormats(),
					vorbis.getSupportedInputFormats(),
			    	PlugInManager.CODEC);
			Renderer videorenderer = new Java2DRenderer();
			
			javax.media.PlugInManager.addPlugIn("com.omnividea.media.renderer.video.Java2DRenderer",
					videorenderer.getSupportedInputFormats(),
					videorenderer.getSupportedInputFormats(),
			    	PlugInManager.RENDERER);
			/*
			Renderer audioRenderer = new JavaSoundRenderer();
			javax.media.PlugInManager.addPlugIn("net.sf.fmj.media.renderer.audio.JavaSoundRenderer",
					audioRenderer.getSupportedInputFormats(),
					audioRenderer.getSupportedInputFormats(),
			    	PlugInManager.RENDERER);
			 */
		
			//Codec c = new javazoom.spi.vorbis.sampled.file.VorbisEncoding();
			//javax.media.PlugInManager.removePlugIn("com.sun.media.renderer.video.LightWeightRenderer",PlugInManager.RENDERER);
			//javax.media.PlugInManager.removePlugIn("com.sun.media.renderer.video.AWTRenderer",PlugInManager.RENDERER);
			javax.media.PlugInManager.getPlugInList(null,null, PlugInManager.RENDERER);
			javax.media.PlugInManager.getPlugInList(null,null, PlugInManager.DEMULTIPLEXER);
			javax.media.PlugInManager.getPlugInList(null,null, PlugInManager.MULTIPLEXER);
			javax.media.PlugInManager.getPlugInList(null,null, PlugInManager.CODEC);
	}
	
	
	public void initializeVideo(){
		URL url;
		addCodec();
		//Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true); 
		try {
			if(StringUtils.isBlank(PATH_OF_AVI_FILE)){
				return;
			}
			
			url = new File(PATH_OF_AVI_FILE).toURI().toURL();
			player1 = Manager.createPlayer(url);
			
			player.setPlayer(player1);
			//player.setControlPanelVisible(false);
				addWindowListener( new WindowAdapter() {
					public void windowClosing( WindowEvent e ) {
						if(player.getState()==Player.Started){
							player.stop();
							player.deallocate();
							player.close();
						}
			            System.exit(0);
					}
				});
				
				player.addControllerListener(new ControllerListener() {
					
					public void controllerUpdate(ControllerEvent arg0) {
						if (arg0 instanceof RealizeCompleteEvent) 
						{
							
							JPanel videoPanel = new JPanel(new FlowLayout());
							//videoPanel.setPreferredSize(new Dimension(800,650));
							JLabel label = new JLabel("aaaaaccccccccccc c ccccccxcxcxcxcx cxcdffjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj dfjh dlkfjh dkhksdh fgfgfgfg");
							label.setFont(new Font("Serif", Font.BOLD, 72));
							label.setForeground(Color.BLACK);
							Component comp;
							videoPanel.removeAll();
							label.setOpaque(false);
							//if ( (comp = player.getVisualComponent()) != null ){
								//comp.setPreferredSize(new Dimension(700,500));
								player.setBounds(10,10,700,500);	
								
								//videoSubPanel.setBounds(10,10,700,500);
								label.setBounds(200,20,660,90);
								//label2.setBounds(20,120,660,90);
								
								
								
								player.setSubtitle();
								videoPanel.add(player);
								//videoPanel.add(label);
								video.add(videoPanel);
								
								
								
				           // }

//				            if ( (comp = player.getControlPanelComponent()) != null ){
//				            	comp.setPreferredSize(new Dimension(400,20));
//				            	video.add(comp);
//				            }
				            validate();
				            
						}
						if (arg0 instanceof PrefetchCompleteEvent){}
						if (arg0 instanceof EndOfMediaEvent){}
						if(arg0 instanceof RestartingEvent){
							System.out.println(player.getMediaTime().getSeconds());
							System.out.println(player.getStartLatency().getSeconds());
							System.out.println(player.getSyncTime().getSeconds());
							
						}
						if(arg0 instanceof MediaTimeSetEvent){
							System.out.println(player.getMediaTime().getSeconds());
							System.out.println(player.getStartLatency().getSeconds());
							System.out.println(player.getSyncTime().getSeconds());
						}
						
					}
				});
			
				player.realize();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (NoPlayerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void eventOnJRadioButtonOne(){
		jRadioOne.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mmStartTime.setEditable(false);
				ssStartTime.setEditable(false);
				milliStartTime.setEditable(false);
				mmEndTime.setEditable(false);
				ssEndTime.setEditable(false);
				milliEndTime.setEditable(false);
				srtFromField.setEditable(true);
				srtUntilField.setEditable(true);
			}
		});
	}

	public void eventOnJRadioButtonTwo(){
		jRadioTwo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mmStartTime.setEditable(true);
				ssStartTime.setEditable(true);
				milliStartTime.setEditable(true);
				mmEndTime.setEditable(true);
				ssEndTime.setEditable(true);
				milliEndTime.setEditable(true);
				srtFromField.setEditable(false);
				srtUntilField.setEditable(false);
			}
		});
	}

	public void eventOnInputFile(){
		inputFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				FileDialog chooser = new FileDialog(SRTTreatement.this);
				chooser.setMode(FileDialog.LOAD);
				chooser.setFilenameFilter(new FilenameFilter() {

					
					public boolean accept(File dir, String name) {
						String extension = SRTUtils.getExtensionOfFile(dir);
						if (extension != null) {
							return extension.equals(SRT);
						}
						return false;
					}
					
				});
				chooser.setVisible(true);
				String fileSelected = chooser.getDirectory()+chooser.getFile();



				if(StringUtils.isNotBlank(fileSelected)){

					File input = new File(fileSelected);
					if(input.getName().toLowerCase().endsWith(SRT)){
						try {
							inputFileField.setText(input.getCanonicalPath());
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						PATH_OF_INPUT_FILE = input.getPath();
					}
					else{
						JOptionPane.showMessageDialog(
								SRTTreatement.this,"This file is nor a SRT", "Not a SRT",
								JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});
	}

	public void eventOnAviInputFile(){
		inputAviFile.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				FileDialog chooser = new FileDialog(SRTTreatement.this);
				chooser.setMode(FileDialog.LOAD);
				chooser.setFilenameFilter(new FilenameFilter() {

					
					public boolean accept(File dir, String name) {
						String extension = SRTUtils.getExtensionOfFile(dir);
						if (extension != null) {
							return extension.equals(AVI);
						}
						return false;
					}
					
				});
				chooser.setVisible(true);
				String fileSelected = chooser.getDirectory()+chooser.getFile();
				File inputAviFile = new File(fileSelected);
				if(inputAviFile!=null){
					PATH_OF_AVI_FILE = inputAviFile.getPath();
					if(player!=null){
						player.deallocate();
						player.close();
					}
					initializeVideo();
				}
			}
		});
	}


	public void eventOnOutputFile(){
		outputFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				FileDialog chooser = new FileDialog(SRTTreatement.this);
				chooser.setMode(FileDialog.SAVE);
				chooser.setFilenameFilter(new FilenameFilter() {

					public boolean accept(File dir, String name) {
						String extension = SRTUtils.getExtensionOfFile(dir);
						if (extension != null) {
							return extension.equals(SRT);
						}
						return false;
					}
				});
				chooser.setVisible(true);
				String fileSelected = chooser.getDirectory()+chooser.getFile();
				if(StringUtils.isNotBlank(fileSelected)){
					File outputFile = new File(fileSelected);

					if(outputFile!=null){
						if(outputFile.exists()){
							int responseFromUser = JOptionPane.showConfirmDialog(SRTTreatement.this,"This File exist ever, do you want overwrite it ?");
							if(responseFromUser == JOptionPane.OK_OPTION){
								outputFileField.setText(outputFile.getPath());
								PATH_OF_OUTPUT_FILE = outputFile.getAbsolutePath();
							}
						}
						else{
							outputFileField.setText(outputFile.getPath());
							PATH_OF_OUTPUT_FILE = outputFile.getPath();
						}

					}
				}
			}
		});
	}

	public void eventOnLaunchButton(){
		launch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					listOfRecord = new ArrayList<SRTRecord>();
					isFirstTime = true;

					if(PATH_OF_INPUT_FILE == null){
						//addMessage();
						return;
					}
					readSubFile();
					if(jRadioOne.isSelected()){
						if(StringUtils.isNotBlank(srtFromField.getText())&&
								StringUtils.isNotBlank(srtUntilField.getText())){

							int gap = SRTUtils.getTotalTimeInMilliSeconds(gapInMinuteField.getText(),gapInSecondsField.getText()
									,gapInMillisecondsField.getText());
							int startPosition = Integer.parseInt(srtFromField.getText());
							int endPosition = Integer.parseInt(srtUntilField.getText());
							addShiftFromSrtNumberToAnotherSrtNumber(gap,startPosition,endPosition);


						}
					}
					else{
						if(jRadioTwo.isSelected()){
							int gap = SRTUtils.getTotalTimeInMilliSeconds(gapInMinuteField.getText(),gapInSecondsField.getText()
									,gapInMillisecondsField.getText());
							int startPosition = SRTUtils.getTotalTimeInMilliSeconds(mmStartTime.getText(),ssStartTime.getText()
									,milliStartTime.getText());
							int endPosition = SRTUtils.getTotalTimeInMilliSeconds(mmEndTime.getText(),ssEndTime.getText()
									,milliEndTime.getText());
							addShiftFromStartTimeToEndTime(gap,startPosition,endPosition);
						}

					}
					writeSubFile();
					JOptionPane.showMessageDialog(SRTTreatement.this,"File "+PATH_OF_OUTPUT_FILE+" created !!!");
				} catch (IOException e1) {
					throw new RuntimeException(e1);
				}
				finally{
					listOfRecord.clear();
				}
			}
		});
	}

	public void eventOnClearButton(){
		clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SRTUtils.clear(inputFileField);
				SRTUtils.clear(outputFileField);
				SRTUtils.clear(srtFromField);
				SRTUtils.clear(srtUntilField);
				SRTUtils.clear(gapInMinuteField);
				SRTUtils.clear(gapInSecondsField);
				SRTUtils.clear(gapInMillisecondsField);
				SRTUtils.clear(mmStartTime);
				SRTUtils.clear(mmEndTime);
				SRTUtils.clear(ssStartTime);
				SRTUtils.clear(ssEndTime);
				SRTUtils.clear(milliStartTime);
				SRTUtils.clear(milliEndTime);
			}
		});
	}

	public void initializeJMenuBar(){
		JMenu main = new JMenu(I18nTranslation.MENU_MAIN);
		JMenu option = new JMenu(I18nTranslation.MENU_OPTION);
		JMenu help = new JMenu(I18nTranslation.MENU_HELP);
		JMenuItem exitItem = new JMenuItem(I18nTranslation.MENU_EXIT);
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		JMenuItem languageItem = new JMenuItem(I18nTranslation.MENU_LANGUAGE);
		languageItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				SRTLanguage language = new SRTLanguage();
			}
		});
		JMenuItem helpItem = new JMenuItem(I18nTranslation.MENU_HELP); 
		helpItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SRTHelp help = new SRTHelp();
			}
		});
		main.add(exitItem);
		option.add(languageItem);
		help.add(helpItem);

		jMenuBar.add(main);
		jMenuBar.add(option);
		jMenuBar.add(help);
	}

	public void initializeGui(){
		JPanel rigthOne = new JPanel();
		JPanel rigthTwo = new JPanel();
		JPanel rigthThree = new JPanel();
		JPanel rigthFour = new JPanel();
		JPanel left = new JPanel();
		JPanel mainPanel = new JPanel();
		

		//video.setLayout(new FlowLayout(FlowLayout.LEADING,20,20));
		left.setLayout(new FlowLayout());
		left.add(inputFile);
		left.add(inputFileField);
		left.add(outputFile);
		left.add(outputFileField);
		left.add(inputAviFile);
		left.add(aviInputFileField);
		rigthOne.setLayout(new FlowLayout());
		rigthOne.add(jRadioOne);
		rigthOne.add(new JLabel(I18nTranslation.SRT_NUMBER_FROM));
		rigthOne.add(srtFromField);
		rigthOne.add(new JLabel(I18nTranslation.SRT_NUMBER_TO));
		rigthOne.add(srtUntilField);
		rigthTwo.setLayout(new FlowLayout());
		rigthTwo.add(jRadioTwo);
		rigthTwo.add(new JLabel(I18nTranslation.SRT_TIME_FROM));
		rigthTwo.add(new JLabel(I18nTranslation.MM));
		rigthTwo.add(mmStartTime);
		rigthTwo.add(new JLabel(I18nTranslation.SS));
		rigthTwo.add(ssStartTime);
		rigthTwo.add(new JLabel(I18nTranslation.MILLI));
		rigthTwo.add(milliStartTime);
		rigthTwo.add(new JLabel(I18nTranslation.SRT_TIME_TO));
		rigthTwo.add(new JLabel(I18nTranslation.MM));
		rigthTwo.add(mmEndTime);
		rigthTwo.add(new JLabel(I18nTranslation.SS));
		rigthTwo.add(ssEndTime);
		rigthTwo.add(new JLabel(I18nTranslation.MILLI));
		rigthTwo.add(milliEndTime);
		rigthThree.setLayout(new FlowLayout());
		rigthThree.add(new JLabel(I18nTranslation.SHIFT_MINUTES));
		rigthThree.add(gapInMinuteField);
		rigthThree.add(new JLabel(I18nTranslation.SHIFT_SECONDS));
		rigthThree.add(gapInSecondsField);
		rigthThree.add(new JLabel(I18nTranslation.SHIFT_MILLISECONDS));
		rigthThree.add(gapInMillisecondsField);

		rigthFour.setLayout(new FlowLayout());
		rigthFour.add(launch);
		rigthFour.add(clear);


		mainPanel.setLayout(new FlowLayout(FlowLayout.CENTER,40,40));
		//video.setPreferredSize(new Dimension(800,650));
		mainPanel.add(video);
		mainPanel.add(left);
		mainPanel.add(rigthOne);
		mainPanel.add(rigthTwo);
		mainPanel.add(rigthThree);
		mainPanel.add(rigthFour);
		initializeJMenuBar();
		this.setJMenuBar(jMenuBar);
		this.add(mainPanel);
		
	}

	

	public void readSubFile() throws IOException{
		File srtFile = new File(PATH_OF_INPUT_FILE);
		BufferedReader bufferedReader = null;
		FileReader reader = null;
		try {
			reader = new FileReader(srtFile);
			bufferedReader = new BufferedReader(reader);
			SRTRecord record = new SRTRecord();
			while(true){
				String line = bufferedReader.readLine();

				if(line == null){
					if(StringUtils.isNotBlank(record.getSubtitleText())){
						listOfRecord.add(record);
						record = new SRTRecord();
					}
					break;
				}
				if(SRTUtils.isNumOfSub(line)){
					if(!isFirstTime){
						listOfRecord.add(record);
						record = new SRTRecord();
					}
					else{
						isFirstTime = false;  
					}
					record.setNumOfSub(Integer.parseInt(line));
				}
				if(SRTUtils.isTimeOfSub(line)){
					record.setStartTimeOfSub(getBeginOfTime(line));
					record.setEndTimeOfSub(getEndOfTime(line));
				}
				if(SRTUtils.isTranslation(line)){
					if(StringUtils.isNotBlank(record.getSubtitleText())){
						record.setSubtitleText(record.getSubtitleText()+" "+line);
					}
					else{
						record.setSubtitleText(line);
					}

				}

			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		finally{
			if(bufferedReader!=null){
			bufferedReader.close();
			}
		}

	}

	public void writeSubFile() throws IOException{
		File srtFile = new File(PATH_OF_OUTPUT_FILE);//TODO to change
		FileWriter writer = null;
		BufferedWriter bufferedWriter = null;
		try {
			writer = new FileWriter(srtFile);
			bufferedWriter = new BufferedWriter(writer);
			for(SRTRecord record : listOfRecord){
				bufferedWriter.write(""+record.getNumOfSub()+SRTUtils.getOneCarriageReturn());
				if(record.getStartTimeOfSub()==null){
					System.out.println();
				}
				bufferedWriter.write(""+SRTUtils.convertCalendarToString(record.getStartTimeOfSub())+" --> "+
						SRTUtils.convertCalendarToString(record.getEndTimeOfSub())+SRTUtils.getOneCarriageReturn());
				bufferedWriter.write(record.getSubtitleText()+SRTUtils.getCarriageReturn(2));
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		finally{
			bufferedWriter.close();
		}
	}


	public void addShiftFromStartTimeToEndTime(int shiftInMillissecond,
			int startPositionInMillissecond,int endPositionInMillissecond){
		List<SRTRecord> cloneList = new ArrayList<SRTRecord>(listOfRecord);
		int indiceStartPosition = 0;
		int indiceEndPosition = cloneList.size();

		for(SRTRecord record : cloneList){
			indiceStartPosition++;
			if(record.getStartTimeOfSub()==null){
				System.out.println();
			}
			if(SRTUtils.getTotalTimeInMilliSeconds(record.getStartTimeOfSub())>startPositionInMillissecond){
				break;
			}
		}
		Collections.reverse(cloneList);
		for(SRTRecord record : cloneList){
			if(SRTUtils.getTotalTimeInMilliSeconds(record.getEndTimeOfSub())<endPositionInMillissecond){
				break;
			}
			indiceEndPosition--;
		}
		addShiftFromSrtNumberToAnotherSrtNumber(shiftInMillissecond,indiceStartPosition,indiceEndPosition);
	}



	public void addShiftFromSrtNumberToAnotherSrtNumber(int shiftInMillissecond,int startPosition,int endPosition){
		Collections.sort(listOfRecord,new Comparator<SRTRecord>() {
			public int compare(SRTRecord o1, SRTRecord o2) {
				return o1.compareTo(o2);
			}
		});

		List<SRTRecord> subList = listOfRecord.subList(startPosition-1, endPosition);
		for(SRTRecord record : subList){
			record.getStartTimeOfSub().add(Calendar.MILLISECOND,shiftInMillissecond);
			record.getEndTimeOfSub().add(Calendar.MILLISECOND,shiftInMillissecond);
		}
	}

	/**
	 * @param line
	 * @return
	 */
	 private Calendar getEndOfTime(String line) {
		 return manipulateLineToExtractTime(1,2,line);
	 }

	 /**
	  * @param line
	  * @return
	  */
	 private Calendar getBeginOfTime(String line) {
		 return manipulateLineToExtractTime(0,2,line);
	 }
	 
	 private Calendar manipulateLineToExtractTime(int posOne,int posTwo,String line){
		 Calendar calendar = new GregorianCalendar(1900,0,0);
		 String[] dateInString = line.split("-->");
		 String[] endtime = dateInString[posOne].split(":");
		 String[] milliSeconde = endtime[posTwo].split(",");
		 calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(endtime[0].trim()));
		 calendar.set(Calendar.MINUTE,Integer.parseInt(endtime[1].trim()));
		 calendar.set(Calendar.SECOND,Integer.parseInt(milliSeconde[0].trim()));
		 calendar.set(Calendar.MILLISECOND,Integer.parseInt(milliSeconde[1].trim()));
		 return calendar;
	 }

	 public void addMessage(String message,Severity severity){
		 JOptionPane.showMessageDialog(SRTTreatement.this, message, "Error",SRTUtils.getSeverity(severity));
	 }



}

